package fun.xiefeihong.utils

import groovy.util.logging.Slf4j

@Slf4j
class SimpleJava2Groovy {

    void java2groovy(String javaFilePath, String groovyFilePath){
        log.info("javaFilePath: $javaFilePath, groovyFilePath: $groovyFilePath")
        def javaDir = new File(javaFilePath)
        if(javaDir.isDirectory()){
            javaDir.listFiles().each { javaFile ->
                if(javaFile.isDirectory()){
                    def groovyFilePath2 = groovyFilePath + (javaFile.path - javaFilePath)
                    new File(groovyFilePath2).mkdirs()
                    java2groovy(javaFile.path, groovyFilePath2)
                } else if(javaFile.isFile()){
                    def javaFileName = javaFile.name
                    def groovyFileName = javaFileName.substring(0, javaFileName.size() - '.java'.size()) + '.groovy'
                    log.info("groovyFileName: $groovyFileName")
                    def groovyFile = new File(groovyFilePath + '/' + groovyFileName)
                    javaFile.eachLine { line ->
                        def tline = line.trim()
                        if(tline.endsWith(';')){
                            line = line.substring(0, line.lastIndexOf(';'))
                        }
                        if(tline.startsWith('public ')){
                            line = line.replaceFirst('public ', '')
                        } else if (tline.startsWith('protected ')){
                            line = line.replaceFirst('protected ', '')
                        } else if (tline.startsWith('private ')){
                            line = line.replaceFirst('private ', '')
                        }
                        groovyFile << line + '\n'
                    }
                    javaFile.delete()
                }
            }
        }
    }

    static void main(String[] args) {
        String projectPath = '/home/xiefeihong/IdeaProjects/demo'
        String javaFilePath = projectPath + '/src/main/java'
        String groovyFilePath = projectPath + '/src/main/groovy'
        def sjg = new SimpleJava2Groovy()
        sjg.java2groovy(javaFilePath, groovyFilePath)
        new File(javaFilePath).deleteDir()
    }

}
